<template>
  <div class="manage">
    <el-card class="box-card">
      <el-dialog
          :title="modelType===0?'新增' : '编辑'"
          :visible.sync="dialogVisible"
          width="50%"
          :before-close="handleClose">
        <el-form ref="form" :rules="rules" :model="form" label-width="120px" class="demo-form-inline">
            <el-form-item label="ID" prop="id">
                <el-input v-model="user.id" placeholder="ID" :disabled="true"></el-input>
            </el-form-item>
            <el-form-item label="请假人" prop="userId">
                <!--            <el-input v-model="form.userId" clearable placeholder="请假人id"></el-input>-->
                <el-select filterable style="width: 400px" v-model="form.userId" clearable placeholder="请选择请假人">
                    <el-option
                            v-for="user in userOptions"
                            :key="user.id"
                            :label="user.name"
                            :value="user.id">
                        <span style="float: left">{{ user.id }}</span>
                        <span style="float: right; color: #8492a6; font-size: 13px">{{ user.name }}</span>
                    </el-option>
                </el-select>
            </el-form-item>
          <el-form-item label="请假类型" prop="type">
            <el-select clearable v-model="form.type" placeholder="请假类型">
              <el-option
                  v-for="item in type"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <!--          <el-form-item label="请假类型" prop="type">-->
          <!--            <el-input v-model="form.type" clearable placeholder="请假类型"></el-input>-->
          <!--          </el-form-item>-->
          <el-form-item label="请假开始时间" prop="startTime">
            <!--            <el-input v-model="form.startTime" clearable placeholder="请假开始时间"></el-input>-->
            <!--            <div class="block">-->
            <el-date-picker
                v-model="form.startTime"
                clearable
                type="datetime"
                placeholder="请假开始时间"
                align="right"
                value-format="yyyy-MM-dd HH:mm:ss"
                :picker-options="pickerOptions"
                @change="handleEndTimeChange">
            </el-date-picker>
            <!--            </div>-->
          </el-form-item>
          <el-form-item label="请假结束时间" prop="endTime">
            <!--            <el-input v-model="form.endTime" clearable placeholder="请假结束时间"></el-input>-->
            <el-date-picker
                v-model="form.endTime"
                clearable
                value-format="yyyy-MM-dd HH:mm:ss"
                type="datetime"
                placeholder="请假结束时间"
                align="right"
                :picker-options="pickerOptions"
                @change="handleEndTimeChange">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="请假天数" prop="duration">
            <el-input :disabled="modelType===0" v-model="form.duration" clearable placeholder="请假天数"></el-input>
          </el-form-item>
          <el-form-item label="请假原因" prop="reason">
            <el-input v-model="form.reason" clearable placeholder="请假原因"></el-input>
          </el-form-item>
          <el-form-item v-if="modelType!==0" label="请假流程状态" prop="status">
            <!--            <el-input v-model="form.status" clearable placeholder="请假流程状态"></el-input>-->
            <el-select clearable v-model="form.status" placeholder="请选择">
              <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
      </el-dialog>
      <div class="manage-header">
        <!--      from搜索区-->
        <el-form ref="queryForm" :inline="true" :model="queryForm" class="demo-form-inline queryForm">
          <el-form-item label="请假日期" prop="startTime">
              <el-date-picker
                      v-model="queryForm.startTime"
                      clearable
                      type="date"
                      placeholder="请假开始时间"
                      align="right"
                      value-format="yyyy-MM-dd"
                      :picker-options="pickerOptions"
                      @change="handleEndTimeChange">
              </el-date-picker>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select clearable size="mini" v-model="queryForm.status" placeholder="请选择">
              <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="mini" @click="onQuerySubmit">查询</el-button>
          </el-form-item>
          <!-- 添加重置按钮 -->
          <el-form-item>
            <el-button size="mini" @click="resetQueryForm">重置</el-button>
          </el-form-item>
        </el-form>
        <el-button style=" margin:0 0 10px 0" size="small" type="primary" @click="handleAdd">新增</el-button>
      </div>
      <div class="common-table">
        <!-- max-height="380"  -->
        <el-table
            :data="tableData"
            stripe
            style="width: 100%">
          <template slot="empty">
            <!--            <img src="../assets/iocnFonts/no-data.png" width="300"/>-->
            <div><span>暂无数据，稍后重试</span></div>
          </template>
          <el-table-column
              prop="userId"
              show-overflow-tooltip
              label="ID"
              width="100">
          </el-table-column>
          <el-table-column
              prop="userId"
              label="姓名"
              width="150"
              :formatter="formatUserId">
          </el-table-column>
          <el-table-column
              prop="type"
              label="请假类型"
              width="80">
          </el-table-column>
          <el-table-column
              prop="startTime"
              label="开始时间"
              width="180">
          </el-table-column>
          <el-table-column
              prop="endTime"
              label="结束时间"
              width="180">
          </el-table-column>
          <el-table-column
              prop="duration"
              label="请假天数"
              width="80">
          </el-table-column>
          <el-table-column
              prop="reason"
              label="请假理由"
              width="280">
          </el-table-column>
          <el-table-column
              prop="status"
              label="请假流程"
              width="180">
          </el-table-column>
          <!--          fixed="right"-->
        </el-table>
      </div>
      <!--分页区-->
      <div class="block" style="margin:20px 0 0 15px ;">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="tablePage.pageNum"
            :page-sizes="[ 5,10, 15,20]"
            :page-size="tablePage.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>


import {addLeave, deleteLeaveById, getLeaveById, getLeaveList, updateLeave} from "@/api/Leave";

export default {
  data() {
    return {
      userOptions:[],
      dialogVisible: false,
      //表单数据
      form: {
        userId: '',
        username: '',
        password: '',
        permission: '',
        remark: ''
      },
      queryForm: {//查询表单数据
        startTime: '',
        status: '',
      },
        user: '',
        roleOptions: [
        {value: 1, label: '管理员'},
        {value: 2, label: '普通员工'}
      ],
      rules: {
        username: [
          {required: true, message: '请输入名称', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 6, message: '长度不小于6位数字', trigger: 'blur'}
        ]
      },
      tableData: [],
      tablePage: {
        pageNum: 1,//当前页
        pageSize: 10,//每页条数
      },
      total: 0,
      modelType: 0,
      type: [{
        value: '事假',
        label: '事假'
      }, {
        value: '病假',
        label: '病假'
      }, {
        value: '工伤假',
        label: '工伤假'
      }, {
        value: '产假',
        label: '产假'
      }, {
        value: '婚假',
        label: '婚假'
      }, {
        value: '丧假',
        label: '丧假'
      }, {
        value: '公假',
        label: '公假'
      }, {
        value: '探亲假',
        label: '探亲假'
      }, {
        value: '年休假',
        label: '年休假'
      }],
      options: [{
        value: '已批准',
        label: '已批准'
      }, {
        value: '待审批',
        label: '待审批'
      }],
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date());
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24);
            picker.$emit('pick', date);
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', date);
          }
        }]
      }
    };
  },
  created() {
      const user = JSON.parse(localStorage.getItem('user'));
      this.user = user;
      if (user) {
          this.userOptions = [user];
      } else {
          this.$message.error('未找到登录用户');
      }
  },
  methods: {
    handleEndTimeChange() {
      const startTime = new Date(this.form.startTime);
      const endTime = new Date(this.form.endTime);
      const diffTime = endTime.getTime() - startTime.getTime();
      const diffDays = diffTime / (1000 * 60 * 60 * 24);
      this.form.duration = Math.ceil(diffDays);
    },
    formatUserId(row) {
        const user = this.userOptions.find(option => option.id === row.userId);
        return user ? user.name : row.userId;
    },
    submit() {
      this.$refs.form.validate((valid) => {
        console.log(valid, 'valid');
        if (valid) {
          if (this.form.duration < 1) {
            this.$message({
              message: '请假天数错误',
              type: 'error'
            });
            return false
          }
          if (this.modelType === 0) {
            addLeave(this.form).then(res => {
              if (res.data.code === 200) {
                this.$message({
                  message: '添加成功',
                  type: 'success'
                });
                this.getList();
              } else {
                // 处理错误情况
                this.$message.error(res.data.message);
              }
              this.$refs.form.resetFields();
              this.dialogVisible = false
            }).catch(err => {
            })
          } else {
            console.log(this.form,'updateLeave')
            updateLeave(this.form).then(res => {
              if (res.data.code === 200) {
                this.$message({
                  message: '修改成功',
                  type: 'success'
                });
                this.getList();
              } else {
                // 处理错误情况
                this.$message.error(res.data.message);
              }
              this.$refs.form.resetFields();
              this.dialogVisible = false
            }).catch(err => {
            })
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 弹窗关闭的时候调用
    handleClose() {
      // 清空表单
      this.form = {}
      this.dialogVisible = false
    },
    cancel() {
      this.handleClose()
    },
    handleEdit(index, row) {
      this.modelType = 1
      this.dialogVisible = true
      getLeaveById(row.id).then(res => {
        console.log(res, 'res')
        this.form = res.data.data
      }).catch(() => {
      })
    },
    handleDelete(index, row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteLeaveById(this.tableData[index].id).then(res => {
          if (res.data.code === 200) {
            this.$message({
              message: '删除成功',
              type: 'success'
            });
            this.getList();
          } else {
            // 处理错误情况
            this.$message.error('操作失败，状态码：' + res.data.code);
          }
        }).catch(err => {
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleAdd() {
      this.dialogVisible = true
      this.modelType = 0
    },
    getList() {
      const params = {
        pageNum: this.tablePage.pageNum,
        pageSize: this.tablePage.pageSize,
        startTime: this.queryForm.startTime,
        status: this.queryForm.status,
        userId: this.user.id
      }
      console.log(params, 'params')
      getLeaveList({params}).then(res => {
        console.log(res, 'res')
        this.tableData = res.data.data
        this.total = res.data.total || 0
      }).catch(() => {
        this.$message.error('获取数据失败')
      })
    },
    handleSizeChange(pageSize) {
      this.tablePage.pageSize = pageSize
      this.getList()//刷新数据
    },
    handleCurrentChange(currentPage) {
      this.tablePage.pageNum = currentPage
      this.getList()//刷新数据
    },
    onQuerySubmit() {
      this.$refs.queryForm.validate((valid) => {
        if (valid) {
          // 提交表单
          this.getList()
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetQueryForm() {
      this.$refs.queryForm.resetFields();
    }
  },
  mounted() {
    this.getList()
  }
}
</script>

<style lang="less" scoped>
.manage {
  height: 90%;

  .common-table {
    position: relative;
    height: calc(100% - 50px);

    /deep/ .el-table td {
      /* 设置表格内容字体居中 */
      text-align: center;
    }

    /deep/ .el-table th {
      /* 设置表头文字居中 */
      text-align: center;
    }
  }
}
</style>
